package com.cool.core.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.Charsets;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author juwencheng
 * @date 2023 2023/2/14 11:14
 */
public class LangTools {

    private Map<String, Map<String, String>> translateMap = new ConcurrentHashMap<>();

    private String langFilePath = "";

    private LangTools() {
    }

    public static LangTools sharedInstance() {
        return LangToolsHolder.instance;
    }

    public static void setLangFilePath(String filePath) {
        LangTools.sharedInstance().langFilePath = filePath;
    }

    /**
     * 支持多语言
     *
     * @return
     */
    public static String m(String message) {
        // 从内存中获取语言版本
        String lang = "";
        Map<String, String> stringStringMap = sharedInstance().translateMap.get(lang);
        if (stringStringMap == null) {
            return message;
        }
        String formatMessage = stringStringMap.getOrDefault(message, "");
        if (StrUtil.isEmpty(formatMessage)) {
            return message;
        }
        return formatMessage;
    }

    public static void refresh() throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream(sharedInstance().langFilePath);
        String read = IoUtil.read(fileInputStream, Charsets.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(read);
        Map<String, Map<String, String>> translateMap1 = sharedInstance().translateMap;
        for (String s : jsonObject.keySet()) {
            if (!s.equals("base")) {
                JSONObject jsonObject1 = jsonObject.getJSONObject(s);
                Map<String, String> inner = new HashMap<>();
                for (String s1 : jsonObject1.keySet()) {
                    inner.put(s1, jsonObject1.getString(s1));
                }
                translateMap1.put(s, inner);
            }
        }
    }

    private static class LangToolsHolder {
        private static LangTools instance = new LangTools();
    }
}
